<template>
  <el-form ref="entityFormRef" :model="entityForm" :rules="entityRules" label-width="100px" :disabled="isView()">
    <el-row>
      <el-col :span="6">
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="entityForm.name" placeholder="请输入名称" maxlength="25" @change="handleFirstPinyin"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="模型编码" prop="code">
          <el-input v-model="entityForm.code" :disabled="pageType !== PageTypeEnum.ADD" placeholder="请输入编码"
                    maxlength="20"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="模型类型" prop="type">
          <el-select v-model="entityForm.dataType" :disabled="pageType !== PageTypeEnum.ADD" @change="handleTypeChange">
            <el-option v-for="dict in sys_def_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="所属主题" prop="areaCode">
          <el-select v-model="entityForm.areaCode" placeholder="--请选择--">
            <el-option v-for="area in areaOptions" :key="area.code" :label="area.name" :value="area.code"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="20">
        <el-form-item label="说明" prop="remark">
          <el-input type="textarea" v-model="entityForm.remark" :rows="2" show-word-limit maxlength="300"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        <el-form-item label="是否扩展" prop="slaveSw">
          <el-switch v-model="entityForm.slaveSw" active-value="1" inactive-value="0" disabled/>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="entityForm.slaveSw === SwitchEnum.OPEN">
        <el-form-item label="主模型" prop="linkCode" filterable>
          <el-select v-model="entityForm.linkCode" placeholder="--请选择--" filterable>
            <el-option v-for="item in modelOptions" :key="item.code" :label="item.name" :value="item.code"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row v-if="entityForm.slaveSw !== SwitchEnum.OPEN">
      <el-col :span="6">
        <el-form-item label="支持分类" prop="classifySw">
          <el-switch v-model="entityForm.classifySw" active-value="1" inactive-value="0"
                     :disabled="entityForm.dataType !== ModeTypeEnum.LIST" @change="handleClassifyChange"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="分类模板" prop="classPropSw">
          <el-switch v-model="entityForm.classPropSw" active-value="1" inactive-value="0"
                     :disabled="entityForm.classifySw !== SwitchEnum.OPEN"/>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="entityForm.classifySw === SwitchEnum.OPEN">
        <el-form-item label="分类模型" prop="linkCode" filterable>
          <el-select v-model="entityForm.linkCode" placeholder="--请选择--" filterable>
            <el-option v-for="item in modelOptions" :key="item.code" :label="item.name" :value="item.code"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        <el-form-item label="默认访问" prop="vipLevel">
          <el-select v-model="entityForm.vipLevel" placeholder="--请选择--">
            <el-option v-for="dict in sys_user_vip" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="物理表映射" prop="physicTable">
          <el-switch v-model="entityForm.swt.physicTable" active-value="1" inactive-value="0"/>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue';
import { ModeTypeEnum } from '@/store/enums/ModeTypeEnum';
import { PageTypeEnum } from '@/store/enums/PageTypeEnum';
import { SwitchEnum } from '@/store/enums/SwitchEnum';
import { listArea } from '@/api/module/area';
import modelApi from '@/api/module/model';
import pinyin from '@/utils/pinyin';

export default defineComponent({
  name: 'ModelBase',
  props: ['pageType', 'model'],
  setup(props) {
    const { proxy } = getCurrentInstance();
    const { pageType, model } = toRefs(props);
    const { sys_user_vip, sys_def_type } = proxy.useDict('sys_user_vip', 'sys_def_type');
    const vueData = reactive({
      modelOptions: [],
      areaOptions: [],
      entityFormTitle: '',
      entityFormOpen: false,
      entityForm: model.value,
      entityRules: {
        code: [
          { required: true, message: '模型编码不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '模型编码长度必须介于 2 和 20 之间', trigger: 'blur' },
          { pattern: /^\w{3,20}$/, message: '只能输入字母和数字' },
        ],
        name: [{ required: true, message: '模型名称不能为空', trigger: 'blur' }],
        areaCode: [{ required: true, message: '主题不能为空', trigger: 'change' }],
        linkCode: [{ required: true, message: '模型不能为空', trigger: 'change' }],
      },
    });

    function loadModelOptions(type) {
      let param = { dataType: type };
      modelApi.listModel(param).then(res => {
        vueData.modelOptions = res.rows;
        vueData.modelOptions.push({ code: '-', name: '默认分类' })
      });
    }

    const handleClassifyChange = () => {
      // 加载选择模型信息
      if (vueData.entityForm.classifySw === SwitchEnum.CLOSE) {
        vueData.modelOptions = [];
      } else {
        loadModelOptions(ModeTypeEnum.TREE); // 接着普通层级模型
      }
    }

    const handleFirstPinyin = (name) => {
      if (pageType.value === PageTypeEnum.ADD) {
        if (vueData.entityForm.code == null || vueData.entityForm.code == '') {
          vueData.entityForm.code = pinyin.getFirstLetter(name);
        }
      }
    }

    const handleTypeChange = (newType) => {
      if (newType !== ModeTypeEnum.LIST && newType !== ModeTypeEnum.TREE) {
        vueData.entityForm.slaveSw = SwitchEnum.OPEN;
      } else {
        vueData.entityForm.slaveSw = SwitchEnum.CLOSE;
      }
    };

    function handleSubmit() {
      proxy.$refs['entityFormRef'].validate(valid => {
        if (valid) {
          if (vueData.entityForm.uid !== '') {
            modelApi.updateModel(vueData.entityForm).then(() => {
              proxy.$modal.msgSuccess('修改成功');
            });
          } else {
            modelApi.addModel(vueData.entityForm).then(res => {
              vueData.entityForm.uid = res.data.uid;
              proxy.$modal.msgSuccess('新增成功');
            });
          }
        }
      });
    }

    const loadAreaList = () => {
      listArea({}).then(res => {
        vueData.areaOptions = res.data;
      });
    };

    const load = () => {
      loadAreaList();
      loadModelOptions();
    };

    function isView() {
      return pageType.value == PageTypeEnum.QUERY;
    }

    return {
      load,
      pageType,
      PageTypeEnum,
      SwitchEnum,
      ModeTypeEnum,
      sys_user_vip,
      sys_def_type,
      ...toRefs(vueData),
      isView,
      handleClassifyChange,
      handleFirstPinyin,
      handleTypeChange,
      handleSubmit,
    }
  },
});
</script>

<style scoped>

</style>